<script setup>
import { computed, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import http from '@/config/axios-config'
import fromLayout from '@/config/form-layout'
import SaveDialog from '@/components/plug-in/save-dialog'

const props = defineProps({
  visible: Boolean,
  form: [Object, Boolean]
})
const emit = defineEmits(['update:visible', 'complete'])
let show = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

let saveForm = ref({})
let saveModal = ref()
let saveLoading = ref(false)
let saveItemLayout = ref(fromLayout)
let isCreate = ref(false)

const submitHandler = () => {
  saveModal.value.validateFields().then(() => {
    saveLoading.value = true
    let url = isCreate.value ? '/role/create' : '/role/update'
    http.post(url, saveForm.value).then(res => {
      saveLoading.value = false
      if (res.code === 200) {
        message.success(res.msg)
        show.value = false
        saveForm.value = {}
        emit('complete')
      }
    })
  }).catch(() => {})
}

watch(() => props.form, () => {
  saveForm.value = props.form ? Object.assign({}, props.form) : {}
  isCreate.value = !props.form
}, { deep: true })

</script>

<template>
  <save-dialog
      v-model:visible="show"
      :title="isCreate ? '添加角色' : '编辑角色'"
      :confirm-loading="saveLoading"
      @ok="submitHandler">
    <div>
      <a-form ref="saveModal" :model="saveForm" v-bind="saveItemLayout">
        <a-form-item name="RoleName" label="角色名" :rules="[{ required: true, message: '请输入角色名' }]">
          <a-input v-model:value="saveForm.RoleName" autocomplete="off"/>
        </a-form-item>
        <a-form-item name="RoleDesc" label="备注" :rules="[{ required: true, message: '请输入角色备注' }]">
          <a-textarea :rows="3" v-model:value="saveForm.RoleDesc"/>
        </a-form-item>
      </a-form>
    </div>
  </save-dialog>
</template>
